import { Component, OnInit } from '@angular/core'
import { Router } from '@angular/router'
import { HttpClientService } from 'src/app/common/httpClient/http'
import { CoolLocalStorage } from 'src/app/common/coolStorage/cool-local-storage'
import { timeout } from 'q'

@Component({
  selector: 'app-splash',
  templateUrl: './splash.component.html',
  styleUrls: ['./splash.component.scss']
})
export class SplashComponent implements OnInit {
  iconShow = false

  constructor(private router: Router, private http: HttpClientService, private storage: CoolLocalStorage) {}

  ngOnInit() {
    let platformId = this.storage.getItem('platformId')
    this.checkPlatform(platformId)
  }
  checkPlatform(platformId) {
    let timeout = 0
    if (platformId === 'android') {
      timeout = 1500
      this.iconShow = true
    } else {
      this.iconShow = false
    }
    setTimeout(() => {
      this.router.navigate(['/workspace/home/index'])
    }, timeout)
  }
  // 获取当前位置
  getCurrentPosition() {
    console.log('正在定位...')
    navigator.geolocation.getCurrentPosition(
      position => {
        this.onSuccess(position)
      },
      error => {
        this.onError(error)
      }
    )
  }
  onSuccess(position) {
    console.log(position)
    this.transformPositon(
      position.coords.latitude,
      position.coords.longitude,
      res => {
        console.log('经纬度转换成功')
        this.reverAddress(
          res.locations[0].lat,
          res.locations[0].lng,
          data => {
            console.log('城市转换成功')
            let city = data.result.ad_info.city
            let lat = data.result.location.lat
            let lng = data.result.location.lng
            let location = { latitude: lat, longitude: lng, city: city }
            this.storage.setObject('location', location)
            this.router.navigate(['/workspace/home/index'])
          },
          () => {
            console.log('城市转换失败')
            this.handleFail()
          }
        )
      },
      () => {
        console.log('经纬度转换失败')
        this.handleFail()
      }
    )
  }
  // 定位失败
  onError(error) {
    console.log('定位失败')
    this.handleFail()
  }
  // 经纬度转换
  transformPositon(lat, lng, callback, errBack?) {
    this.http.get(
      `https://apis.map.qq.com/ws/coord/v1/translate?locations=${lat},${lng}&type=1&key=KPJBZ-TIR6R-YTPWI-WER7Z-QP3J3-KIBI3`,
      callback,
      errBack
    )
  }
  // 逆地址解析
  reverAddress(lat, lng, callback, errBack?) {
    this.http.get(
      `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=KPJBZ-TIR6R-YTPWI-WER7Z-QP3J3-KIBI3`,
      callback,
      errBack
    )
  }
  // 统一失败处理
  handleFail() {
    this.router.navigate(['/workspace/home/index'])
  }
}
